package me.raih.controller.sales;

import com.alibaba.fastjson.JSONObject;
import me.raih.pojo.po.*;
import me.raih.pojo.vo.Manager;
import me.raih.pojo.vo.PageBean;
import me.raih.pojo.vo.ResultInfo;
import me.raih.pojo.vo.SellWares;
import me.raih.service.BillService;
import me.raih.service.SalaryService;
import me.raih.service.UserService;
import me.raih.service.WaresService;
import me.raih.util.MathUtil;
import me.raih.util.TimeUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author Raih
 * @Time 2020/12/31 16:00
 *
 * 售货员业务
 */
@Controller
@RequestMapping(value = "/sales")
public class SalesController {

    @Autowired
    ResultInfo resultInfo;

    @Autowired
    WaresService waresService;

    @Autowired
    BillService billService;

    @Autowired
    UserService userService;

    @Autowired
    SalaryService salaryService;

    @Autowired
    Bill bill;

    @Autowired
    Manager manager;

    /**
     * 售货员售货时候 找寻每个商品
     * @param no
     * @return
     */
    @RequestMapping(value = "/findWares",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo wares(@RequestParam("number") String no){

        Wares wares = waresService.findWaresByNo(no);


        if(wares == null){
            resultInfo.setFlag(false);
            resultInfo.setMessage("该商品不存在请检查");
        }else {
            resultInfo.setFlag(true);
            resultInfo.setData(wares);
        }

        return resultInfo;
    }

    /**
     * 结账
     * @param sellWaresList
     * @param allPrice
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sellWares",method = RequestMethod.PUT)
    public ResultInfo byWares(@RequestParam("waresList")String sellWaresList,
                              @Param("allPrice") double allPrice,
                              HttpSession session,
                              @RequestParam("username")String username,
                              @RequestParam("allPoint")double allPoint){
        //将JSON字符串转换成对象
        List<SellWares> sellWares = JSONObject.parseArray(sellWaresList, SellWares.class);
        //创建订单对象
        bill.setBillNo(TimeUtils.createBillNo());
        //获取当前时间
        bill.setCreateTime(new Date());
        //设置总积分
        bill.setPoints(allPoint);
        Sales sales = (Sales) session.getAttribute("SALES_LOGIN_SESSION_FLAG");
        //设置售货员名
        bill.setSales(sales);
        bill.setSalesName(sales.getUsername());
        Map<String,Integer> sellMaps = new HashMap<>();
        for (SellWares sellWare : sellWares) {
            String no = sellWare.getNo();
            //将数量和商品编号放入map中
            sellMaps.put(no,sellWare.getNumber());
        }
        //设置售出的商品
        bill.setSellWaresMap(sellMaps);
        bill.setSellWaresMapStr(sellMaps.toString());
        //判断是否是打折日，然后设置总价
        //获取 map
        Map<String, Double> forSale = manager.getForSale();
        //只有一个，所以获取第一个字符
        String next = forSale.keySet().iterator().next();
        if("YES".equals(next)){
            //如果是打折日子，获取 折扣
            Double discount = forSale.get(next);
            allPrice = MathUtil.twoDoubleNumber(allPrice * discount);
        }
        bill.setAllPrice(allPrice);
        //设置购买人的姓名
        bill.setUserName(username);
        //尝试添加订单到数据库中
        boolean flag = billService.canCreateBill(bill);
        //尝试给用户添加积分
        if(username != null && username.length() > 0){
            boolean flag2 = userService.addUserPoint(username,allPoint);
            flag = flag && flag2;
        }
        if(flag){
            resultInfo.setFlag(true);
            resultInfo.setMessage("购买成功!");
        }else {
            resultInfo.setFlag(false);
            resultInfo.setMessage("出单失败，请刷新页面重新购买");
        }
        return resultInfo;
    }

    /**
     * 通过手机号查询用户信息
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/phoneFindUser",method = RequestMethod.PUT)
    public ResultInfo phoneGetUser(@RequestParam("phone") long phone){

        User user = userService.findUserByPhone(phone);

        if(user != null){
            resultInfo.setFlag(true);
            resultInfo.setData(user);
        }else {
            resultInfo.setFlag(false);
        }
        return resultInfo;
    }

    /**
     * 根据条件查询订单
     * @param billNo
     * @param currentPage
     * @param param
     * @param pageSize
     * @param username
     * @param bigPage
     * @return
     */
    @RequestMapping(value = "/findBillPage",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo findBill(HttpServletRequest request,
                               @RequestParam("billNo")String billNo,
                               @RequestParam("currentPage")int currentPage,
                               @RequestParam("param")String param,
                               @RequestParam("pageSize")String pageSize,
                               @RequestParam("username")String username,
                               @RequestParam("bigPage")int bigPage){

        int pageSizeInt;
        try {
            pageSizeInt = Integer.parseInt(pageSize);
        }catch (Exception e){
            pageSizeInt = 5;
        }
        PageBean<Bill> billPageBean = billService.findBillByBillNoAndPageAndUsername(billNo,currentPage,bigPage,param,pageSizeInt,username);

        if(billPageBean.getList() == null || billPageBean.getList().size() == 0){
            resultInfo.setFlag(false);
            resultInfo.setMessage("没有数据可以查询！");
        }else {
            resultInfo.setFlag(true);
            resultInfo.setData(billPageBean);
            //把所有的订单放到session中
            request.getSession().setAttribute("BILL_WARES_MESSAGE",billPageBean.getList());
        }

        return resultInfo;
    }


    @RequestMapping(value = "/findSalary",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo findSalary(@RequestParam("time")String time,HttpServletRequest request){

        //获取当前管理员信息
        Sales sales = (Sales)request.getSession().getAttribute("SALES_LOGIN_SESSION_FLAG");
        /*
        *
        * 这里要username  而不是要 name
        * */
        String salesName = sales.getUsername();
        //通过售货员名和时间获取工资信息
        List<Salary> salaryList = salaryService.findSalaryMessageByUsernameAndTime(salesName,time);

        if (salaryList == null || salaryList.size() == 0){
            resultInfo.setMessage("没有查到数据");
            resultInfo.setFlag(false);
        } else {
            resultInfo.setData(salaryList);
            resultInfo.setFlag(true);
        }
        return resultInfo;
    }

    @RequestMapping(value = "/salesMessageModify")
    public String toUpdate(HttpServletRequest request){

        //获取当前售货员信息
        Sales sales = (Sales)request.getSession().getAttribute("SALES_LOGIN_SESSION_FLAG");
        //通过信息
        request.setAttribute("SALES_EDIT",sales);

        return "sales/salesModify";
    }

    @RequestMapping(value = "/modifySalesMessage",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo modifyMessage(Sales sales){
        int i = salaryService.updateSalesBySales(sales);

        if(i == 1){
            resultInfo.setFlag(true);
            resultInfo.setMessage("修改成功啦！");
        }else {
            resultInfo.setFlag(false);
            resultInfo.setMessage("修改失败，请联系管理员重新修改");
        }
        return resultInfo;
    }


}
